package com.wwlwxg.dataStructure;

import java.util.Scanner;

/**
 * 数组实现的队列
 * 定长
 * TODO 没有同步功能
 */
public class ArrayQueue<E> {

	private int maxSize;    // 表示数组的最大容量
	private int producePos;       // 队列生产pos
	private int consumePos;       // 队列消费pos
	private Object[] arr;      // 该数组用于存放数据，模拟队列

	public ArrayQueue(int maxSize) {
		this.maxSize = maxSize;
		this.arr = new Object[maxSize];
		producePos = -1;      // 指向队列生产pos
		consumePos = -1;      // 指向队列消费pos
	}

	public static void main(String[] args) {
		ArrayQueue queue = new ArrayQueue(3);
		queue.add(1);
		queue.add(2);
		queue.add(3);
		queue.add(4);

		queue.poll();
		queue.poll();

		queue.showAllData();

		queue.showAvailableData();

		queue.peek();
		queue.peek();

	}

	public boolean isFull() {
		return producePos == maxSize - 1;
	}

	public boolean isEmpty() {
		return producePos == consumePos;
	}

	public void add(int n) {
		if(isFull()) {
			System.out.println("队列满了，不能加入数据");
			return;
		}
		System.out.println("添加数据 " + n + " 成功");
		producePos++;
		arr[producePos] = n;
	}

	public E poll() {
		if(isEmpty()) {
			throw new RuntimeException("队列为空，不能poll数据");
		}
		consumePos++;
		System.out.println("poll 数据 " + arr[consumePos]);
		return (E)arr[consumePos];
	}

	public void showAvailableData() {
		if(isEmpty()) {
			System.out.println("队列为空，没有数据");
			return;
		}
		System.out.println("队列中的可用数据为：");
		for(int i = consumePos + 1; i <= producePos; i++) {
			System.out.printf("arr[%d] = %d\n", i, arr[i]);
		}
	}

	public void showAllData() {
		if(isEmpty()) {
			System.out.println("队列为空，没有数据");
			return;
		}
		System.out.println("队列中的所有数据为：");
		for(int i = 0; i < arr.length; i++) {
			System.out.printf("arr[%d] = %d\n", i, arr[i]);
		}
	}

	public E peek() {
		if(isEmpty()) {
			throw new RuntimeException("队列为空，没有数据");
		}
		int index = consumePos + 1;
		System.out.println("peek的数据为：" + arr[index]);
		return (E)arr[index];
	}
}
